﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=T_RES_LINK;
    locationTable=T_RES_LOCATION;

    topicModel=new QStringListModel(this);
    ui->topicView->setModel(topicModel);

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    startSynchronizer();
    updateTopicView();
    createMenu();
    loadLocation();
}

Widget::~Widget()
{
    saveLocation();
    delete ui;
}

void Widget::startSynchronizer()
{
    synchronizer=new LocationSynchronizer;
    connect(this,&Widget::add_path,
            synchronizer,&LocationSynchronizer::add_path);
    connect(this,&Widget::remove_path,
            synchronizer,&LocationSynchronizer::remove_path);
    synchronizer->awake(table,locationTable);
}

void Widget::openTopicLocation()
{
    if(topicDetails.isEmpty())
        return;

    QModelIndex index=ui->topicView->currentIndex();
    if(index.isValid())
    {
        QString label=index.data().toString();
        QString detail=topicDetails.value(label);
        if(detail.isEmpty())
            return;
        if(QDir(detail).exists())
            QDesktopServices::openUrl(QUrl::fromLocalFile(detail));
    }
}

void Widget::updateTopicView()
{
    if(!topicDetails.isEmpty())
        topicDetails.clear();

    QSqlQuery query;
    query.exec(QString("select label,detail from %1 where category='Location'")
               .arg(table));
    while (query.next()) {
        QString label=query.value(0).toString();
        QString detail=query.value(1).toString();
        topicDetails.insert(label,detail);
    }
    if(!topicDetails.isEmpty())
        topicModel->setStringList(topicDetails.keys());
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("更新目录"),
                    this,&Widget::updateTopicView);
    menu->addAction(QStringLiteral("更新列表"),
                    this,&Widget::updateLocationView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("打开目录"),
                    this,&Widget::openTopicLocation);
    menu->addAction(QStringLiteral("显示无标签条目"),
                    this,&Widget::showUnfinished);
    menu->addSeparator();
    QMenu *m_setting=menu->addMenu(QStringLiteral("设置"));
    m_setting->addAction(QStringLiteral("添加目录..."),
                         this,&Widget::addPath);
    m_setting->addAction(QStringLiteral("删除目录"),
                         this,&Widget::removePath);
}

void Widget::addPath()
{
    QString path=QFileDialog::getExistingDirectory(this,QStringLiteral("选择一个目录"),
                                                   Location::video);
    if(path.isEmpty())
        return;

    QString dirName=QDir(path).dirName();
    addItem("Location",dirName,path);
    updateTopicView();
    emit add_path(path);
}

void Widget::removePath()
{
    QModelIndex index=ui->topicView->currentIndex();
    if(index.isValid())
    {
        QString label=index.data().toString();
        if(topicDetails.contains(label))
        {
            QString detail=topicDetails.value(label);
            emit remove_path(detail);
        }
    }
}

bool Widget::updateItem(const QString &tag)
{
    if(selectLabel.isEmpty())
        return false;

    QSqlQuery query;
    QString sql=QString("update %1 set addition='%2' where label='%3'")
            .arg(locationTable)
            .arg(tag)
            .arg(selectLabel);

    if(query.exec(sql))
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void Widget::on_btn_save_clicked()
{
    QString tag=ui->tag->toPlainText();
    if(selectTag.isEmpty() || tag != selectTag)
        updateItem(tag);
}

void Widget::on_search_returnPressed()
{
    if(selectTopic.isEmpty() || selectLabel.isEmpty())
        return;

    QString kw=ui->search->text().trimmed();
    if(!kw.isEmpty())
    {
        if(!itemDetails.isEmpty())
            itemDetails.clear();

        QSqlQuery query;
        query.exec(QString("select label,detail from %1 where category='%2' AND (addition like '%%3%' OR label like '%%3%')")
                   .arg(locationTable)
                   .arg(selectTopic)
                   .arg(kw));

        while (query.next()) {
            QString label=query.value(0).toString();
            QString detail=query.value(1).toString();
            itemDetails.insert(label,detail);
        }
        if(!itemDetails.isEmpty())
            listModel->setStringList(itemDetails.keys());
    }
}

void Widget::showUnfinished()
{
    listModel->setStringList(QStringList());

    if(selectTopic.isEmpty())
        return;

    if(!itemDetails.isEmpty())
        itemDetails.clear();

    QSqlQuery query;
    query.exec(QString("select label,detail from %1 where category='%2' AND addition IS NULL")
               .arg(locationTable)
               .arg(selectTopic));

    while (query.next()) {
        QString label=query.value(0).toString();
        QString detail=query.value(1).toString();
        itemDetails.insert(label,detail);
    }
    if(!itemDetails.isEmpty())
        listModel->setStringList(itemDetails.keys());
}

void Widget::updateLocationView()
{
    if(selectTopic.isEmpty())
        return;

    if(!itemDetails.isEmpty())
        itemDetails.clear();

    QSqlQuery query;
    query.exec(QString("select label,detail from %1 where category='%2'")
               .arg(locationTable)
               .arg(selectTopic));

    while (query.next()) {
        QString label=query.value(0).toString();
        QString detail=query.value(1).toString();
        itemDetails.insert(label,detail);
    }
    if(!itemDetails.isEmpty())
        listModel->setStringList(itemDetails.keys());
}

void Widget::on_topicView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectTopic=index.data().toString();
        updateLocationView();
    }
}

void Widget::on_listView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectLabel=index.data().toString();
        QSqlQuery query;
        query.exec(QString("select detail,addition from %1 where category='%2' AND label='%3'")
                   .arg(locationTable)
                   .arg(selectTopic)
                   .arg(selectLabel));
        if(query.next())
        {
            QString file=query.value(0).toString();
            QFileInfo fileInfo(file);
            if(fileInfo.exists())
            {
                QString fileSize=QStringLiteral("文件大小： ") +
                        QString::number(fileInfo.size() / 1024 / 1024) +
                        QString("MiB");

                ui->info->setPlainText(fileSize);
            }
            ui->tag->setPlainText(query.value(1).toString());
        }
    }
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString label=index.data().toString();
        QString detail=itemDetails.value(label);
        if(detail.isEmpty())
            return;

        if(QFile::exists(detail))
            QDesktopServices::openUrl(QUrl::fromLocalFile(detail));
    }
}
